package com.wuge.service.impl;

import com.alibaba.fastjson.JSON;
import com.wuge.common.to.es.SkuEsModel;
import com.wuge.service.ProductSaveService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.*;

@Service
public class ProductSaveServiceImpl implements ProductSaveService {
    @Resource
   private RestHighLevelClient restHighLevelClient;
    @Override
    public boolean saveSku(List<SkuEsModel> list) {
        BulkRequest bulkRequest=new BulkRequest();
        for (SkuEsModel skuEsModel : list) {
            IndexRequest indexRequest=new IndexRequest("mall_product");
            indexRequest.id(skuEsModel.getSkuId().toString());
            String s = JSON.toJSONString(skuEsModel);
            indexRequest.source(s,XContentType.JSON);
            bulkRequest.add(indexRequest);
        };
        boolean b=false;
        BulkResponse bulk ;
        try {
           bulk= restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            b=!bulk.hasFailures();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return b;
    }
//    public static void main(String[] args) throws InterruptedException {
//
//        ExecutorService executorService = Executors.newCachedThreadPool();
//        CompletableFuture<String> stringCompletableFuture = CompletableFuture.supplyAsync(() -> {
//            try {
//                Thread.sleep(10);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            System.out.println(Thread.currentThread().getId());
//            return "888";
//        }, executorService).whenComplete((key,exception)->{
//            System.out.println("异步线程"+Thread.currentThread().getId());
//            System.out.println(key);
//            exception.getCause();
//        });
//        System.out.println("主线程"+Thread.currentThread().getId());
//    }

}
